import { Emiter } from "@Tea/utils";
import { ElPagination } from "element-plus";
import { CSSProperties, reactive, PropType, defineComponent, computed, ref, watch, isRef, Ref } from "vue";
import classes from './index.module.scss'
import { VxeTable, VxeTableInstance, VxeColumn, VxeColumnProps } from "vxe-table";
import "./index.scss"
import { VxeTableProps } from "vxe-table/types/table";
import { ChooseRequired } from "@Tea/model";

type PaginationConfig = {
  tableName: string,
  pageSizes: number[]
}

export type TableConfigType<TData> = ChooseRequired<VxeTableProps<TData>, "data">
export type TableV2Type<TData = any> = {
  tableConfig: TableConfigType<TData> | Ref<TableConfigType<TData>>,
  colmunConfig: (VxeColumnProps | (Omit<VxeColumnProps, 'type'>&{ type:'slot', vNode: (context) =>JSX.Element}))[]
} 

function usePagination(config: PaginationConfig) {
   // 注册订阅事件
  const emiter = Emiter.getInstance()
  const currentPage = ref(1)
  const pageSize = ref(config?.pageSizes[0] || 100)
  const total = ref(0)
  const pageSizes = ref(config.pageSizes || [100, 200, 300, 400])

  const handleSizeChange = (val: number) => {
    pageSize.value = val
    emiter.emit(config.tableName, `onSearch`)
  }

  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    emiter.emit(config.tableName, `onSearch`)
  }

 
  
  // 重置页数
  emiter.on(config.tableName, `resetCurPage`, () => {
      currentPage.value = 1
  })

  //获取currentPage pageSize
  emiter.on(config.tableName, `getCurAndSize`, () => ({
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }))

  //设置条数
  emiter.on(config.tableName, `setTotal`, (num: number) => {
    total.value = num
  })

  // 设置PageSize 
  emiter.on(config.tableName, 'setPageSize', (sizes: number[])=> {
    pageSizes.value = sizes
  })

  return { currentPage, pageSize, pageSizes, total, handleSizeChange, handleCurrentChange }
}

function useVexTable(config: TableV2Type["tableConfig"], tableName:string) {
  const xTable = ref<VxeTableInstance>()
  //
  const xParent = ref<HTMLDivElement>()

  const rowData = ref((isRef(config)? config.value.data : config.data) || []); 

  const defaultColumn: VxeColumnProps = {
    width: 250,
    resizable: true
  }

  const defaultTable: VxeTableProps = {
    border:"full"
  }

  const emitter = Emiter.getInstance()
  emitter.on(tableName, "setRowData", (data: any[]) => {
    rowData.value = data
  })
  // 获取单选项
  emitter.on(tableName, "getRadioSelected", () => xTable.value.getRadioRecord())
  // 获取复选项
  emitter.on(tableName, "getCheckboxRecords", () => xTable.value.getCheckboxRecords())
  // 打开所有
  emitter.on(tableName, "setAllTreeExpand",(checked: boolean = true) => xTable.value.setAllTreeExpand(checked))
  // 关闭所有
  emitter.on(tableName, "clearTreeExpand", () => xTable.value.clearTreeExpand())
  // 全选
  emitter.on(tableName, 'setAllCheckboxRow', (checked: boolean = true) => xTable.value.setAllCheckboxRow(checked))
  // 清除选择
  emitter.on(tableName, 'clearCheckboxRow', () => xTable.value.clearCheckboxRow())
  
  return {
    xTable,
    xParent,
    rowData,
    defaultColumn,
    defaultTable
  }
}

export default defineComponent({
  props: {
    tableClass: String,
    tableStyle: {
      type: Object as PropType<CSSProperties>
    },
    initPagination: {
      type: Boolean,
      default: true
    },
    pagintionAttr: {
      type: Object as PropType<Omit<PaginationConfig, "tableName">>,
      default: {
        pageSizes: [100, 200, 300, 400]
      }
    },
    tableName: {
      type: String,
      required: true,
    },
    vexTableV2: {
      type: Object as PropType<TableV2Type>,
      required: true
    }
  },
  setup(props, ctx) {
    const {
      currentPage, pageSize, total, pageSizes,
      handleSizeChange, handleCurrentChange
    } = usePagination({
      tableName: props.tableName,
      pageSizes: props.pagintionAttr.pageSizes
    })

    const {
      xTable,
      xParent,
      rowData,
      defaultColumn,
      defaultTable
    } = useVexTable(props.vexTableV2.tableConfig, props.tableName)

    return () => {
      return (
        <div class={`${props.tableClass || ''} ${classes.table} m-window defaultCustem defaultThame`} style={props.tableStyle || {}}>
          <div class={`ag-theme-balham ${classes.VxeTable}`} ref={xParent} style={{ flex: 1, }}>
            <VxeTable
              border="default"
              maxHeight={computed(() => xParent.value?.clientHeight).value}
              ref={xTable}
              {...{
                ...Object.assign(
                  {},
                  defaultTable,
                  isRef(props.vexTableV2.tableConfig) ? props.vexTableV2.tableConfig.value : props.vexTableV2.tableConfig
                ),
                data: rowData.value,
              }}
            >
              {
                props.vexTableV2.colmunConfig.map((column) => (
                  column.type === 'slot' ?
                    <VxeColumn {...Object.assign({}, defaultColumn, column as any)} v-slots={{
                      default: (context) => {
                        return column.vNode(context)
                      }
                    }}></VxeColumn>
                    : <VxeColumn {...Object.assign({}, defaultColumn, column)}>
                    </VxeColumn>
                ))
              }
            </VxeTable>
          </div>
          {
            props.initPagination && (
              <div class={`m-top ${classes.pagination}`}>
                <ElPagination
                  v-model:pageSize={pageSize.value}
                  v-model:currentPage={currentPage.value}
                  layout="total,sizes, pager,jumper"
                  total={total.value}
                  pageSizes={pageSizes.value}
                  background
                  small
                  {
                  ...{
                    "onSize-change": handleSizeChange,
                    "onCurrent-change": handleCurrentChange
                  }
                  }
                />
              </div>
            )}
        </div>
      )
    }
  },
})